import { defineStore } from 'pinia'
import { UserLoginAPI } from '@/api/user'
import { asyncRoutes , routes , anyRouter } from '@/router/routes'
import router from '@/router'
//封装函数，筛选要展示的路由
 function filterRouters(router){
    let resRouter = router.map(item=>{
        return item.mValue
    })
    //过滤异步路由
    let filterAsyncRouter = asyncRoutes.filter(item=>{
        return resRouter.includes(item.name)
    })
    return [...filterAsyncRouter]
}
const useUserStore = defineStore('userStore',{
    state:()=>{
        return {
            userInfo:localStorage.getItem('userStore') ? JSON.parse(localStorage.getItem('userStore')) : {},
            routeList:localStorage.getItem('routeList') ? JSON.parse(localStorage.getItem('routeList')) : [],
            users:'',
        }
    },
    actions:{
        async userLogin(data){
            if(data!==undefined) {
                localStorage.setItem('mm',JSON.stringify(data))
            }
            let result = await UserLoginAPI(data?data:JSON.parse(localStorage.getItem('mm')))
            if(data!==undefined) {
                   this.userInfo = result.data
            localStorage.setItem('userStore',JSON.stringify(result.data))
            }
            this.users = result.data
            
            this.routeList = [...routes,...filterRouters(this.users.menus),...anyRouter]
            console.log(this.routeList);
            [...filterRouters(this.users.menus),...anyRouter].forEach(item=>{
                router.addRoute(item)
            })
            localStorage.setItem('routeList',JSON.stringify(this.routeList))
           
       },
       logOut() {
           this.userInfo = {}
           this.routeList = []
           localStorage.removeItem('userStore')
           localStorage.removeItem('routeList')
           asyncRoutes.forEach(item=>{
           
               router.removeRoute(item.name)
           })
          

       }
    },
    getters:{

    },
    //开启数据持久化
    // persist:{
    //     enabled:true
    // }
})

export default useUserStore